package com.example.gustavo.hello.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.gustavo.hello.R;
import com.example.gustavo.hello.model.SmsObj;
import com.example.gustavo.hello.utils.SmsUtil;
import com.example.gustavo.hello.utils.StreamUtil;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 批量发送短信
 */
public class SendSMSActivity extends ActionBarActivity {

    private static final String TAG = "SendSMSActivity";
    private int count = 10;//每次发送的数量
    private int sent_count;//已发送
    private int send_total;//要发送的总量
    private String content;//发送内容
    private String phone;//附加手机号
    private List<String> phoneList;
    private EditText et_phone;
    private EditText et_content;
    private TextView tv_info,tv_total,et_count;
    private ListView listView;
    private List<SmsObj> dataList;
    private BaseAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_sms);

        EventBus.getDefault().register(this);

        et_phone = (EditText) findViewById(R.id.et_phone);
        et_content = (EditText) findViewById(R.id.et_content);
        tv_info = (TextView) findViewById(R.id.tv_info);
        tv_total = (TextView) findViewById(R.id.tv_total);
        et_count = (TextView) findViewById(R.id.et_count);
        listView = (ListView) findViewById(R.id.lv);


        dataList = new ArrayList<>();
        adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return dataList.size();
            }

            @Override
            public Object getItem(int position) {
                return position;
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder viewHolder;

                if(convertView == null ){

                    viewHolder = new ViewHolder();
                    convertView = LayoutInflater.from(SendSMSActivity.this).inflate(R.layout.sms_item, parent, false);
                    viewHolder.tv_phone = (TextView) convertView.findViewById(R.id.tv_phone);
                    viewHolder.tv_sent = (TextView) convertView.findViewById(R.id.tv_sent);
                    viewHolder.tv_received = (TextView) convertView.findViewById(R.id.tv_received);
                    viewHolder.btn_send = (Button) convertView.findViewById(R.id.btn_send);

                    convertView.setTag(viewHolder);

                }else{

                    viewHolder = (ViewHolder) convertView.getTag();
                }

                final SmsObj smsObj = dataList.get(position);
                if (smsObj != null) {

                    viewHolder.tv_phone.setText(smsObj.getPhone());
                    if(smsObj.isSent()){
                        viewHolder.tv_sent.setText("已发送");
                    }else{
                        viewHolder.tv_sent.setText("发送失败");

                    }

                    if(smsObj.isReceived()){
                        viewHolder.tv_received.setText("收到");
                        viewHolder.btn_send.setVisibility(View.INVISIBLE);
                    }else{
                        viewHolder.tv_received.setText("未收到");
                        viewHolder.btn_send.setVisibility(View.VISIBLE);
                    }


                    viewHolder.btn_send.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            SmsUtil.sendSMS(SendSMSActivity.this, smsObj.getPhone(), content);

                        }
                    });

                }


                return convertView;
            }
        };
        listView.setAdapter(adapter);

    }
    class ViewHolder{

        TextView tv_phone,tv_sent,tv_received;
        Button btn_send;

    }

    public void onEventMainThread(SmsObj smsObj){

        if (smsObj != null) {

            boolean exit = false;


            for (SmsObj obj : dataList) {

                if(obj.getPhone().equals(smsObj.getPhone())){

                    obj.setReceived(smsObj.isReceived());
                    exit = true;
                }
            }

            if(!exit){
                dataList.add(smsObj);
            }


        }

        adapter.notifyDataSetChanged();


    }



    private void sendSms(){

        if(TextUtils.isEmpty(et_phone.getText().toString().trim())){
            Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(et_content.getText().toString().trim())){
            Toast.makeText(this,"内容不能为空",Toast.LENGTH_SHORT).show();
            return;
        }


        phone = et_phone.getText().toString().trim();
        content = et_content.getText().toString().trim();
        count = Integer.parseInt(et_count.getText().toString().trim());


        if(phoneList != null && phoneList.size() > 0 ){


            for (int i = 0; i < count; i++) {
                System.out.println("i = " + i);

                if(i < phoneList.size()){

                    SmsUtil.sendSMS(SendSMSActivity.this, phoneList.get(i), content);
                    sent_count++;
                    System.out.println("i = " + i+" phone="+phoneList.get(i)+" sent="+sent_count);
                    tv_info.setText(String.valueOf(sent_count));

                }else{
                    Toast.makeText(this,"发送完成",Toast.LENGTH_SHORT).show();
                }

            }
            System.out.println(" phone="+phone);
            SmsUtil.sendSMS(SendSMSActivity.this,phone,content);




        }else{
            Toast.makeText(this,"没有读取到文件内容",Toast.LENGTH_SHORT).show();
        }
    }




    public void getFile(View view){

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");

        startActivityForResult(intent,0);

    }


    //发送
    public void send(View view){

        if(sent_count < send_total){
            if(sent_count == 0){

                sendSms();
            }else{

                if(phoneList != null){

                    if(phoneList.size() > count){

                        phoneList = phoneList.subList(count,phoneList.size());
                        sendSms();
                    }else{

                        Toast.makeText(this,"发送完成",Toast.LENGTH_SHORT).show();

                    }

                }else{
                    Toast.makeText(this,"请先选择文件",Toast.LENGTH_SHORT).show();
                }

            }

        }else{

            Toast.makeText(this,"发送完成",Toast.LENGTH_SHORT).show();
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data != null) {
            Uri uri = data.getData();

            Log.i(TAG, data.toString());

            if (uri != null) {

                try {
                    InputStream inputStream = getContentResolver().openInputStream(uri);

                    int available = inputStream.available();
                    System.out.println("available = " + available);
                    String s = StreamUtil.readInputStream(inputStream);
                    System.out.println("s = " + s);
                    phoneList = Arrays.asList(s.split(","));
                    if(phoneList != null && phoneList.size() > 0){

                        send_total = phoneList.size();
                        tv_total.setText(send_total+"");
                        sent_count = 0;
                    }else{
                        Toast.makeText(this,"文件读取失败,请重新选择文件",Toast.LENGTH_SHORT).show();
                    }




                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_send_sm, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
